<template>
	<w-app-container class="app-home">
		<fx-page-header title="产线"></fx-page-header>
		<fxListFilter @resetSearch='resetSearch'>
				<template slot="row-1" >
					<el-form-item label="产线：">
						<!-- <w-select ref='productionLineSelect' multiple clearable collapseTags :optionlist='productionLineList'>
						</w-select> -->
						<w-select-mulity
							ref='productionLineSelect'
							:optionlist="productionLineList"
							class="form-input"
						>
						</w-select-mulity>
					</el-form-item>
					<el-form-item label="产线类型：" label-width="110px">
						<!-- <w-select ref='productionLineTypeSelect' multiple clearable collapseTags :optionlist='productionLineTypeList'>
						</w-select> -->
						<w-select-mulity
							ref='productionLineTypeSelect'
							:optionlist="productionLineTypeList"
							class="form-input"
						>
						</w-select-mulity>
					</el-form-item>
					<el-form-item label="启停状态：" label-width="110px">
						<el-select v-model="enableState" prop="enableState" placeholder="请选择" clearable size='mini' class="form-input">
							<el-option
								v-for="item in stateList"
								:key="item.id"
								:label="item.label"
								:value="item.id"
							>
							</el-option>
						</el-select>
					</el-form-item>
				</template>
				<template slot="tools">
					<el-row>
						<el-button type="primary" size='mini' @click="searchProductionline">查询</el-button>
						<el-button type="text" size='mini' @click="resetSearch">重置</el-button>
					</el-row>
				</template>
		</fxListFilter>
		<w-app-container direction="row" class="fx-page-first-container">
			<div class="tree-container">
				<fxTree :treeData="treeData" @node-click="nodeClick"></fxTree>
			</div>
			<w-table
				ref="multipleTable"
				:listData="productionLineData"
				:tableColumn="productionLineColumns"
				:showPagination="true"
				:showColumnFilterBtn="false"
				minWidth="100px"
				:listTotal="totalCount"
				@on-table-row-dbclick="editRow"
				@on-size-change="handleSizeChange"
				@on-current-change="handleCurrentChange">
				<div slot="btn-tools-right" class="tools-right">
						<el-button type="danger" plain size='mini' @click="mutileDel">删除</el-button>
						<el-button type="success" plain size='mini' @click="mutileEnable">启用</el-button>
						<el-button type="info" plain size='mini' @click="mutileDiable">停用</el-button>
						<el-button type="primary"	size='mini' icon="el-icon-plus">导入产线</el-button>
						<el-button type="primary"	size='mini' icon="el-icon-plus" @click="addProductionline">新建产线</el-button>
				</div>
			</w-table>
		</w-app-container>
		<el-dialog :title="dialogTitle" :visible.sync="productionLineInfoDialogVisible" width='480px'	:before-close="beforeClose">
			<div class="create-area">
			<el-form :model="ProductionlineForm" label-position='right' label-width='100px' :rules="ProductionlineRules" ref="ProductionlineForm" size='mini'>
				<el-form-item label="产线编号" prop="code" label-width="110px">
					<el-input v-model="ProductionlineForm.code" autocomplete="off" class="form-item-input"></el-input>
				</el-form-item>
				<el-form-item label="产线名称" prop="name" label-width="110px">
					<el-input v-model="ProductionlineForm.name" autocomplete="off" class="form-item-input"></el-input>
				</el-form-item>
				<el-form-item label="产线类型" prop="productionLineTypeId" label-width="110px">
					<w-select :multiple='false' v-model="ProductionlineForm.productionLineTypeId" allowCreate
					:clearable='true' :collapseTags='false' :optionlist='productionLineTypeList' :isBlock='true' @blur="carTypeBlur" class="form-item-input">
					</w-select>
				</el-form-item>
				<el-form-item label="所属车间" prop="carRoomId" label-width="110px">
					<w-select :multiple='false' v-model="ProductionlineForm.carRoomId"
					:clearable='true' :optionlist='productionLineCarRoomList' :isBlock='true' class="form-item-input">
					</w-select>
				</el-form-item>
				<el-form-item label="联系人" prop="contactName" label-width="110px">
					<el-input v-model="ProductionlineForm.contactName" autocomplete="off" class="form-item-input"></el-input>
				</el-form-item>
				<el-form-item label="电话" prop="mobile" label-width="110px">
					<el-input v-model="ProductionlineForm.mobile" autocomplete="off" class="form-item-input"></el-input>
				</el-form-item>
				<el-form-item label="启停状态" prop="enable" label-width="110px">
					<el-switch v-model="ProductionlineForm.enable" active-color="#13ce66" inactive-color="#ff4949" active-value="1" inactive-value="0"></el-switch>
				</el-form-item>
				<el-form-item label="备注" prop="remark" label-width="110px">
					<el-input
						v-model="ProductionlineForm.remark"
						type="textarea"
						:rows="3"
						:maxlength="200"
						placeholder="请输入备注"
						class="form-item-input"
						show-word-limit
						resize="none"
					/>
				</el-form-item>
			</el-form>
			</div>
			<div slot="footer" class="dialog-footer">
				<el-button @click="doClose">取 消</el-button>
				<el-button type="primary" @click="doSave('ProductionlineForm')">保 存</el-button>
			</div>
		</el-dialog>
	</w-app-container>
</template>
<script>
import fxListFilter from '@/components/common/Fx-list-filter.vue'
import fxTree from '@/components/common/Fx-tree.vue'
import APP_STATE_CONFIG from '@/config/app_state_config.js'
import FxListStateTag from '@/components/common/Fx-list-state-tag.vue'
export default {
	name: 'productionLine',
	components: {
		fxListFilter,
		fxTree
	},
	data () {
		return {
			tableHeight: (document.body.clientHeight - 200) + 'px',
			treeData: [],
			selTreeNode: '',
			stateList: APP_STATE_CONFIG.enableState,
			productionLineList: [],
			productionLineTypeList: [],
			productionLineCarRoomList: [],
			enableState: '',
			productionLineData: [],
			productionLineColumns: [
				{ prop: 'code', label: '产线编码', required: true, width: '80px' },
				{ prop: 'name', label: '产线名称', required: true, showOverflowTooltip: true },
				{ prop: 'carRoomName', label: '所属车间', required: true, showOverflowTooltip: true },
				{ prop: 'productionLineTypeName', label: '产线类型', required: true, showOverflowTooltip: true },
				{
					prop: 'enable',
					label: '启停状态',
					required: true,
					fxRender: this.enableRender
				},
				{ prop: 'remark', label: '备注', required: true, showOverflowTooltip: true },
				{
					prop: 'modifyUser', label: '修改人', required: true
				},
				{
					prop: 'modifyDate', label: '修改时间', required: true
				},
				{
					prop: 'createUser', label: '创建人', required: true
				},
				{
					prop: 'createDate', label: '创建时间', required: true
				}
			],
			totalCount: 0,
			productionLineInfoDialogVisible: false,
			dialogTitle: '',
			ProductionlineForm: {
				code: '',
				name: '',
				productionLineTypeId: '',
				carRoom: '',
				enable: '1',
				remark: ''
			},
			addProductionlineTypeName: '',
			ProductionlineRules: {
				code: [
					{ required: true, message: '请输入产线编号', trigger: 'change' },
					{ min: 1, max: 18, message: '长度最多18个字符', trigger: 'blur' }
				],
				name: [
					{ required: true, message: '请输入产线名称', trigger: 'change' },
					{ min: 1, max: 50, message: '长度最多50个字符', trigger: 'blur' }
				],
				carTypeId: [
					{ min: 1, max: 50, message: '长度最多50个字符', trigger: 'blur' }
				],
				contactName: [
					{ min: 1, max: 50, message: '长度最多50个字符', trigger: 'blur' }
				],
				mobile: [
					{ min: 1, max: 20, message: '长度最多20个字符', trigger: 'blur' }
				],
				carRoomId: [
					{ required: true, message: '请选择所属车间', trigger: 'change' }
				],
				remark: [
					{ min: 1, max: 200, message: '长度最多200个字符', trigger: 'blur' }
				]
			},
			fxDataVerification: null
		}
	},
	created () {
		// 获取左侧树数据
		this.getTreeData()
		// 获取产线下拉选择项
		this.getProductionline()
		this.getProductionlineType()
		this.onRefreshProductionlineList()
	},
	computed: {
		enableFormaterState (val, key) {
			return (val, key) => {
				return this.$fxStateMiddleware.getStateObj('enableState')(val)[key]
			}
		}
	},
	methods: {
		// 树节点点击
		nodeClick (data, node) {
			this.selTreeNode = data.id
			this.onRefreshProductionlineList()
		},
		getTreeData () {
			this.getTreeDataPost().then(res => {
				this.treeData = res
			})
		},
		getTreeDataPost () {
			return new Promise(resolve => {
				this.$fxApi('workshop.orginTree')({
					query: {
						level: '3'
					}
				}).then(res => {
					resolve(res)
				})
			})
		},
		getProductionline () {
			this.getAllProductionlineList().then(res => {
				this.productionLineList = res
			})
		},
		getProductionlineType () {
			return new Promise(resolve => {
				this.getAllProductionlineType().then(res => {
					this.productionLineTypeList = res
					resolve(res)
				})
			})
		},
		// 获取产线下拉选择数据
		getAllProductionlineList () {
			return new Promise(resolve => {
				this.$fxApi('productionLine.findListAll').then(res => {
					resolve(res)
				})
			})
		},
		// 获取产线类型
		getAllProductionlineType () {
			return new Promise(resolve => {
				this.$fxApi('productionLine.findProductionLineTypeListAll').then(res => {
					resolve(res)
				})
			})
		},
		// 获取产线所属车间
		getCarRoomList () {
			return new Promise(resolve => {
				this.$fxApi('workshop.findCarRoomListAll').then(res => {
					resolve(res)
				})
			})
		},
		// 列表数据
		onRefreshProductionlineList () {
			const searchParams = {
				pageNum: (this.$refs.multipleTable && this.$refs.multipleTable.getPaginationParams().pageNum) || 1,
				pageSize: (this.$refs.multipleTable && this.$refs.multipleTable.getPaginationParams().pageSize) || 20
			}
			var params = {}
			if (this.enableState !== '') {
				params.enable = this.enableState
			}
			// 产线下拉
			if (this.$refs.productionLineSelect && this.$refs.productionLineSelect.currentValue.length >= 1) {
				params.productionLineIds = this.$refs.productionLineSelect.currentValue
			}
			// 产线类型下拉
			if (this.$refs.productionLineTypeSelect && this.$refs.productionLineTypeSelect.currentValue.length >= 1) {
				params.productionLineTypeIds = this.$refs.productionLineTypeSelect.currentValue
			}
			if (this.selTreeNode) {
				params.treeId = this.selTreeNode
			}
			if (Object.keys(params).length !== 0) {
				searchParams.params = params
			}
			return new Promise(resolve => {
				this.$fxApi('productionLine.findAllProductionLines')({
					data: searchParams
				}).then(res => {
					this.totalCount = this.$fxUtils.toNumber(res.total)
					this.productionLineData = res.data
					// this.$refs.multipleTable.clearSelected()
					resolve()
				})
			})
		},
		handleSizeChange (val) {
			this.onRefreshProductionlineList()
		},
		handleCurrentChange (val) {
			this.onRefreshProductionlineList()
		},
		addProductionline () {
			return new Promise(resolve => {
				Promise.all([
					this.getAllProductionlineType(),
					this.getCarRoomList(),
					this.getNextCode()
				]).then(([shoplist, carRoomlist, newCode]) => {
					this.productionLineTypeList = shoplist
					this.productionLineCarRoomList = carRoomlist
					this.showDialog(newCode)
					resolve()
				})
			})
		},
		showDialog (code) {
			this.productionLineInfoDialogVisible = true
			if (this.$refs.ProductionlineForm) {
				this.$refs.ProductionlineForm.resetFields()
			}
			this.ProductionlineForm.code = code
			this.ProductionlineForm.id = ''
			this.addProductionlineTypeName = ''
			this.fxDataVerification = this.$fxUtils.fxDataVerification(this.ProductionlineForm)
			this.dialogTitle = '新建产线'
		},
		renderProductionlineInfo (res) {
			const { code, id, contactName, enable, mobile, name, remark, carRoomId, productionLineTypeId } = res
			this.ProductionlineForm = {
				code,
				id,
				contactName,
				enable,
				mobile,
				name,
				remark,
				carRoomId,
				productionLineTypeId
			}
			this.ProductionlineForm.enable = res.enable ? '1' : '0'
			this.fxDataVerification = this.$fxUtils.fxDataVerification(this.ProductionlineForm)
		},
		doClose () {
			this.VerityCompanyData()
		},
		beforeClose () {
			this.VerityCompanyData()
		},
		VerityCompanyData () {
			const isChange = !this.fxDataVerification.checkData(this.ProductionlineForm)
			if (isChange) {
				this.$fxCommon.orderListFrontFunc('VeritybeforeClose').then(() => {
					this.doSave('ProductionlineForm')
				}).catch(() => {
					this.productionLineInfoDialogVisible = false
				})
				return false
			} else {
				this.productionLineInfoDialogVisible = false
			}
		},
		// 产线类型 失去焦点
		carTypeBlur (e, value) {
			if (value) {
				this.addProductionlineTypeName = value
			}
		},
		doSave (formName) {
			this.$refs[formName].validate((valid) => {
				if (valid) {
					this.saveOrUpdateProductionline().then(this.$fxCommon.orderSuccess('save')).then(() => {
						this.productionLineInfoDialogVisible = false
						this.onRefreshProductionlineList()
					})
				} else {
					return false
				}
			})
		},
		editRow (row, column, event) {
			this.productionLineInfoDialogVisible = true
			this.dialogTitle = '修改产线'
			return new Promise(resolve => {
				Promise.all([
					this.getAllProductionlineType(),
					this.getCarRoomList(),
					this.findGroupDetailById(row)
				]).then(([shoplist, carRoomlist, detail]) => {
					this.productionLineTypeList = shoplist
					this.productionLineCarRoomList = carRoomlist
					this.renderProductionlineInfo(detail)
					resolve()
				})
			})
			// this.findGroupDetailById(row).then(this.renderProductionlineInfo)
		},
		// 批量删除
		mutileDel () {
			const _selData = this.$refs.multipleTable.selectedRowArr
			return this.$fxCommon.orderListFrontFunc('deleteMulity', _selData)
				.then(this.deleteProductionline)
				.then(this.$fxCommon.orderSuccess('deleteMulity'))
				.then(this.onRefreshProductionlineList)
		},
		// 批量启用
		mutileEnable () {
			const _selData = this.$refs.multipleTable.selectedRowArr
			return this.$fxCommon.orderListFrontFunc('enableMulity', _selData).then(() => {
				this.handleState(1).then(this.$fxCommon.orderSuccess('enableMulity')).then(this.onRefreshProductionlineList)
			})
		},
		// 批量停用
		mutileDiable () {
			const _selData = this.$refs.multipleTable.selectedRowArr
			return this.$fxCommon.orderListFrontFunc('disableMulity', _selData).then(() => {
				this.handleState(0).then(this.$fxCommon.orderSuccess('disableMulity')).then(this.onRefreshProductionlineList)
			})
		},
		// 启用 停用
		handleState (type) {
			const _selData = this.$refs.multipleTable.selectedRowArr
			const ids = _selData.map(productionLine => productionLine.id)
			return new Promise(resolve => {
				this.$fxApi('productionLine.updateEnable')({
					data: {
						productionLineIds: ids,
						enable: type
					}
				}).then(res => {
					resolve(res)
				})
			})
		},
		resetSearch () {
			this.enableState = ''
			this.$refs.productionLineSelect.currentValue = []
			this.$refs.productionLineTypeSelect.currentValue = []
		},
		// 查询集团
		searchProductionline () {
			this.onRefreshProductionlineList()
		},
		// 获取编号
		getNextCode () {
			return new Promise(resolve => {
				this.$fxApi('productionLine.getNextCode').then(res => {
					resolve(res)
				})
			})
		},
		// 获取集团信息
		findGroupDetailById (row) {
			return new Promise(resolve => {
				this.$fxApi('productionLine.findProductionLineDetailById')({
					query: {
						id: row.id
					}
				}).then(res => {
					resolve(res)
				})
			})
		},
		// 新建更新集团信息
		saveOrUpdateProductionline () {
			const { code, id, contactName, enable, mobile, name, remark, carRoomId } = this.ProductionlineForm
			const postData = {
				id,
				code,
				contactName,
				enable,
				mobile,
				name,
				remark,
				carRoomId
			}
			// 当是新建产线类型的时候
			if (this.addProductionlineTypeName) {
				postData.archiveTypeDTO = {
					id: '',
					name: this.addProductionlineTypeName
				}
			} else {
				if (this.ProductionlineForm.productionLineTypeId) {
					postData.archiveTypeDTO = {
						id: this.ProductionlineForm.productionLineTypeId,
						name: ''
					}
				}
			}
			return new Promise(resolve => {
				this.$fxApi('productionLine.saveOrUpdate')({
					data: postData
				}).then(res => {
					resolve(res)
				})
			})
		},
		// 删除集团信息
		deleteProductionline () {
			const _selData = this.$refs.multipleTable.selection
			const ids = []
			_selData.forEach((v) => {
				ids.push(v.id)
			})
			return new Promise(resolve => {
				this.$fxApi('productionLine.deleteMulity')({
					data: {
						productionLineIds: ids
					}
				}).then(res => {
					resolve(res)
				})
			})
		},
		enableRender (h, { row }) {
			return <FxListStateTag
				icon={this.enableFormaterState(row.enable, 'icon')}
				label={this.enableFormaterState(row.enable, 'label')}
			></FxListStateTag>
		}
	}
}
</script>
<style lang="stylus" scoped>
@import '~$assets/stylus/varsty.styl'
.create-area {
	width: 100%
	height: 400px
	box-sizing: border-box
	.form-item-input {
		width:280px
	}
}
.tree-container {
	display: flex
}
.form-input {
	width: 170px
}
</style>
